package com.example.demo.util.mybatisplus;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.demo.domain.base.BaseDO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * DefaultDBFieldHandler
 *
 * @author hao.chen
 * @date 2023/6/3 14:53
 */
@Component
public class DefaultDBFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseDO) {
            BaseDO baseDO = (BaseDO) metaObject.getOriginalObject();

            Date current = new Date();
            baseDO.setGmtCreate(current);
            baseDO.setGmtModified(current);
            baseDO.setIsDelete(0);


            String userIdStr = Optional.ofNullable(StpUtil.getLoginIdDefaultNull())
                    .filter(id -> id instanceof Long)
                    .map(id -> String.valueOf((Long) id))
                    .orElse("system");

            baseDO.setCreator(userIdStr);
            baseDO.setLastModified(userIdStr);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseDO) {
            BaseDO baseDO = (BaseDO) metaObject.getOriginalObject();

            Date current = new Date();
            baseDO.setGmtModified(current);

            String userIdStr = Optional.ofNullable(StpUtil.getLoginIdDefaultNull())
                    .filter(id -> id instanceof Long)
                    .map(id -> String.valueOf((Long) id))
                    .orElse("system");

            baseDO.setLastModified(userIdStr);

        }
    }
}
